package cn.jcby.app.lebu.controller;


import cn.jcby.app.lebu.controller.req.BasicListReq;
import cn.jcby.app.lebu.controller.req.RechargeReq;
import cn.jcby.app.lebu.entity.UserChargeWithdrawalEntity;
import cn.jcby.app.lebu.enums.OrderStatusEnum;
import cn.jcby.app.lebu.service.UserChargeWithdrawalService;
import cn.jcby.app.lebu.utils.PageUtils;
import cn.jcby.app.lebu.utils.Result;
import cn.jcby.app.lebu.utils.XMLUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;
import org.jdom.JDOMException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.Map;


/**
 * 充值记录
 *
 * @author lht
 * @email 
 * @date 2023-12-07 15:13:35
 */
@RestController
@RequestMapping("charge/withdrawal")
@Api(tags="充值记录")
public class UserChargeWithdrawalController {
    @Autowired
    private UserChargeWithdrawalService userChargeWithdrawalService;

    /**
     * 充值提现记录
     */
    @PostMapping("/list")
    @ApiOperation("充值提现列表")
    @ApiResponses({
          @ApiResponse(code = 200,message = "ok",response = UserChargeWithdrawalEntity.class)
    })
    public Result list(@RequestBody BasicListReq params){
        PageUtils page = userChargeWithdrawalService.queryPage(params);
        return Result.ok().put("data", page);
    }
    //充值、提现
    @PostMapping("/recharge")
    @ApiOperation("充值")
    public Result add(@RequestBody RechargeReq req, HttpServletRequest request) throws Exception {
        Map<String, String> body = userChargeWithdrawalService.recharge(req,request);
        return Result.ok().put("data", body);
    }
    @PostMapping("/withdrawal")
    @ApiOperation("提现")
    public Result update(@RequestBody UserChargeWithdrawalEntity userChargeWithdrawal){
        userChargeWithdrawalService.updateBy(userChargeWithdrawal);
        return Result.ok();
    }

    //回调函数
    @PostMapping("/callback")
    @ApiOperation("回调函数")
    public Result callback(HttpServletRequest request, HttpServletResponse response) throws IOException, JDOMException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        InputStream inStream = request.getInputStream();
        ByteArrayOutputStream outSteam = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outSteam.write(buffer, 0, len);
        }
        System.out.println("~~~~~~~~~~~~~~~~付款成功~~~~~~~~~");
        outSteam.close();
        inStream.close();
        String result = new String(outSteam.toByteArray(), "utf-8");// 获取微信调用我们notify_url的返回信息
        Map<String, Object> map = XMLUtil.doXMLParse(result);
        if (map != null) {
            // 获取返回参数
            String retCode = map.get("return_code").toString();
            String resCode = map.get("result_code").toString();
            // 判断签名及结果
            if ("SUCCESS".equals(retCode) && "SUCCESS".equals(resCode)) {
                // 自定义参数1-案例，2-单商家订单3：多商家订单
                String attach = map.get("attach").toString();// 自定义参数
                //String orderNum = map.get("out_trade_no").toString().substring(0, 18);// 订单号
                String outTradeNo = map.get("out_trade_no").toString();
                String transactionId = map.get("transaction_id").toString();// 交易单号
                String total_fee = map.get("total_fee").toString();// 金额
                /**
                 * 此处写回调业务逻辑
                 */
                userChargeWithdrawalService.updateStatusByTradeNo(outTradeNo,transactionId, OrderStatusEnum.RECHARGE_SUCCESS.getCode()) ;
                System.out.println("修改订单状态成功");
                out.write(XMLUtil.setXML("SUCCESS", "")); // 告诉微信服务器，我收到信息了，不要在调用回调action了
                System.out.println("orderNum-------------" +outTradeNo+","+ XMLUtil.setXML("SUCCESS", ""));
            }
        }
        return Result.ok("支付成功");
    }
}
